import { getRouteListApi, IUserInfo, userLoginApi } from '@/service/user';
import { message } from 'antd';
import { Effect, history, Reducer } from 'umi';
export interface UserModeState {
  userInfo: IUserInfo | null;
}

interface UserModelType {
  namespace: 'user';
  state: UserModeState;
  reducers: {
    updateUserProfile: Reducer<UserModeState>;
  };
  effects: {
    login: Effect;
  };
}
const UserMode: UserModelType = {
  namespace: 'user',
  state: {
    userInfo: sessionStorage.getItem('userProfile') ? JSON.parse(sessionStorage.getItem('userProfile')!) : null,
  },
  reducers: {
    updateUserProfile: (state, { payload }) => ({ ...state, ...payload }),
  },

  effects: {
    *login({ payload }, { put, call, select }) {
      const { data, msg } = yield call(userLoginApi, payload);
      if (!data) {
        message.error(msg);
        return;
      }

      sessionStorage.setItem('userProfile', JSON.stringify(data));
      yield put({
        type: 'updateUserProfile',
        payload: { userInfo: data },
      });
      message.success('登入成功');
      // - 请求成功之后进行路由表的获取
      getRouteListApi().then((res) => {
        const routeData = res.data;
        sessionStorage.setItem('routeList', JSON.stringify(routeData));
        history.push(routeData[0].route);
      });
    },
  },
};

export default UserMode;
